package Service;

import Controller.*;
import Data.*;
import MyInterfaces.MassageType;
import javafx.application.Platform;
import javafx.scene.control.Alert;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

public class ClientConnectionServer implements Runnable{
    private Socket socket;
    private String userid;

    public ClientConnectionServer(Socket socket, String userid) {
        this.socket = socket;
        this.userid = userid;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    @Override
    public void run() {
        try {
            event massage;
            while(!Thread.currentThread().isInterrupted())
            {
                ObjectInputStream reader=new ObjectInputStream(socket.getInputStream());
                massage=(event) reader.readObject();
                if(massage.getType().equals(MassageType.Return_Init_Information))
                {
                    event finalMassage = massage;
                    Platform.runLater(() -> {
                        //获得相应的控制类改变
                        ChatMain chatMainController= Main.AllContronller.getChatMainController();
                        FriendListData friendListData=(FriendListData) finalMassage.getT();
                        System.out.println(friendListData.getMydata().getAvatar()+" "+friendListData.getMydata().getUserNickName());
                        chatMainController.setChatStage(friendListData.getMydata(),friendListData.getFriendList());
                    });
                }
                else if(massage.getType().equals(MassageType.Send_Massage_To_One))
                {
                    MassageData massageData=(MassageData) massage.getT();
                    System.out.println("收到了来自"+massageData.getSender()+"发送给"+massageData.getReceiver()+"的消息"+massageData.getContent());
                    ChatMain chatMain= Main.AllContronller.getChatMainController();
                    chatMain.getMsgList().addOneMsg(massageData.getSender(),massageData);

                    ChatWithStage chatWithStage= Main.AllContronller.getChatWithStageById(massageData.getSender());
                    if(chatWithStage!=null)
                    {
                        Platform.runLater(() -> {
                            System.out.println("在显示消息了"+massageData.getSender());
                            chatWithStage.addMassage(massageData);
                        });
                    }
                    else
                    {
                        System.out.println("是空的控制类哦");
                    }
                }
                else if(massage.getType().equals(MassageType.Return_Send_Massage_Success))
                {
                    MassageData massageData=(MassageData) massage.getT();

                    ChatMain chatMain= Main.AllContronller.getChatMainController();
                    Platform.runLater(() -> {
                        chatMain.getMsgList().addOneMsg(massageData.getReceiver(),massageData);
                    });

                    ChatWithStage chatWithStage= Main.AllContronller.getChatWithStageById(massageData.getReceiver());
                    if(chatWithStage!=null)
                    {
                        Platform.runLater(() -> {
                            chatWithStage.addMassage(massageData);
                        });
                    }
                    else
                    {
                        System.out.println("是空的控制类哦");
                    }
                }
                else if(massage.getType().equals(MassageType.Agree_Add_Friend)||massage.getType().equals(MassageType.Fresh_Friend_Status))
                {
                    PrivateInformationData data=(PrivateInformationData) massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.addFriend(data);
                    });
                }
                else if(massage.getType().equals(MassageType.Send_File_Success)||massage.getType().equals(MassageType.Send_File_Fail))
                {
                    MassageData massageData=(MassageData) massage.getT();
                    ChatWithStage chatWithStage=Main.AllContronller.getChatWithStageById(massageData.getReceiver());
                    event finalMassage5 = massage;
                    Platform.runLater(() -> {
                    chatWithStage.ResultSendFile(finalMassage5);
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Send_File_To_Group_Success)||massage.getType().equals(MassageType.Return_Send_File_To_Group_Fail))
                {
                    MassageData massageData=(MassageData) massage.getT();
                    System.out.println(massageData.getSender()+"发送给"+massageData.getReceiver()+massageData.getFile_name()+"的文件");
                    GroupStage groupStage=Main.AllContronller.getGroupStage(massageData.getReceiver());
                    if(groupStage!=null)
                    {
                        event finalMassage3 = massage;
                        Platform.runLater(() -> {
                            groupStage.ResultSendFile(finalMassage3);
                        });
                    }
                    else
                    {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.getMsgList().addOneMsg(massageData.getReceiver(),massageData);
                    }
                }
                else if(massage.getType().equals(MassageType.Return_Get_File_Success)||massage.getType().equals(MassageType.Return_Get_File_Fail))
                {
                    PutFile putFile=new PutFile(massage);
                    putFile.putFileToMe();
                }
                else if(massage.getType().equals(MassageType.Add_Friend_Success)||massage.getType().equals(MassageType.Add_Friend_Fail))
                {
                    System.out.println(massage.getType());
                    event finalMassage4 = massage;
                    Platform.runLater(() -> {
                    AddFriend addFriend= Main.AllContronller.getAddFriendController();
                    addFriend.ResultAddFriend(finalMassage4);
                    });
                }
                else if(massage.getType().equals(MassageType.Delete_Friend))
                {
                    String id=(String) massage.getT();
                    ChatMain chatMain=Main.AllContronller.getChatMainController();
                    Platform.runLater(() -> {
                        chatMain.delFriend(id);
                    });
                }
                else if(massage.getType().equals(MassageType.Set_All_Group))
                {
                    System.out.println("设置群聊列表");
                    ArrayList<GroupData> list= (ArrayList<GroupData>) massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.setGroupStage(list);
                    });
                }
                else if(massage.getType().equals(MassageType.Add_Group))
                {
                    GroupData groupData=(GroupData) massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.AddGroup(groupData);
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Creat_Group_Success))
                {
                    GroupData groupData=(GroupData) massage.getT();
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("成功");
                        alert.setHeaderText(null);
                        alert.setContentText("创建成功!");
                        alert.showAndWait();
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.AddGroup(groupData);
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Creat_Group_Fail))
                {
                    Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("失败");
                    alert.setHeaderText(null);
                    alert.setContentText("创建失败!");
                    alert.showAndWait();
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Send_Massage_Fail))
                {
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("失败");
                        alert.setHeaderText(null);
                        alert.setContentText("发送失败!");
                        alert.showAndWait();
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Search_Friend_Success)||massage.getType().equals(MassageType.Return_Search_Friend_Fail))
                {
                    event finalMassage2 = massage;
                    Platform.runLater(() -> {

                    AddFriend addFriend= Main.AllContronller.getAddFriendController();
                    addFriend.ReturnAddResult(finalMassage2);
                    });
                }
                else if(massage.getType().equals(MassageType.Search_Group_Success)||massage.getType().equals(MassageType.Search_Group_Fail))
                {
                    AddFriend addgroup=Main.AllContronller.getAddgroup();

                    event finalMassage6 = massage;
                    Platform.runLater(() -> {
                        addgroup.ReturnAddResult(finalMassage6);
                    });
                }
                else if(massage.getType().equals(MassageType.Add_Group_Success)||massage.getType().equals(MassageType.Add_Group_Fail))
                {
                    event finalMassage4 = massage;
                    Platform.runLater(() -> {
                        AddFriend addgroup= Main.AllContronller.getAddgroup();
                        addgroup.ResultAddFriend(finalMassage4);
                    });
                }
                else if(massage.getType().equals(MassageType.Change_Group_Information_Success))
                {
                    GroupData groupData=(GroupData) massage.getT();
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("成功");
                        alert.setHeaderText(null);
                        alert.setContentText("修改成功!");
                        alert.showAndWait();
                        GroupStage groupStage=Main.AllContronller.getGroupStage(groupData.getGroup_id());
                        groupStage.changeStage(groupData);
                    });
                }
                else if(massage.getType().equals(MassageType.Change_Group_Information))
                {
                    GroupData groupData=(GroupData) massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.changeGroupData(groupData);
                    });
                }
                else if(massage.getType().equals(MassageType.Change_Is_Online))
                {
                    PrivateInformationData privateInformationData=(PrivateInformationData)massage.getT();
                    ChatMain chatMain=Main.AllContronller.getChatMainController();
                    Platform.runLater(() -> {
                        chatMain.changeIsOnlie(privateInformationData);
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Send_TO_Group_Massage_Success))
                {
                    //成功啦
                    MassageData massageData=(MassageData) massage.getT();

                    ChatMain chatMain=Main.AllContronller.getChatMainController();
                    chatMain.getMsgList().addOneMsg(massageData.getReceiver(),massageData);

                    Platform.runLater(() -> {
                        GroupStage groupStage=Main.AllContronller.getGroupStage(massageData.getReceiver());
                        if(groupStage!=null)
                        {
                            groupStage.addOneMassage(massageData);
                        }
                    });
                }
                else if(massage.getType().equals(MassageType.Send_Massage_To_Group))
                {
                    //得到了群聊消息的回应，刷新界面
                    System.out.println("收到了群聊消息");
                    MassageData massageData=(MassageData) massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        GroupStage groupStage=Main.AllContronller.getGroupStage(massageData.getReceiver());

                        if(groupStage!=null)
                        {
                            groupStage.addOneMassage(massageData);
                        }
                    });
                }
                else if(massage.getType().equals(MassageType.Change_Group_Information_Fail))
                {
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("失败");
                        alert.setHeaderText(null);
                        alert.setContentText("修改失败!");
                        alert.showAndWait();
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Chat_Massage))
                {
                    event finalMassage8 = massage;
                    Platform.runLater(() -> {
                    //获得聊天初始化界面
                    MassageListData massageListData=(MassageListData) finalMassage8.getT();
                    //往里面追加数据
                    ChatMain chatMain= Main.AllContronller.getChatMainController();
                    chatMain.getMsgList().addToMap(massageListData.getReceiver_id(),massageListData);
                    System.out.println("正在读取记录");
                        System.out.println(massageListData.getReceiver_id());
                        ChatWithStage chatWithStage= Main.AllContronller.getChatWithStageById(massageListData.getReceiver_id());
                        if(chatWithStage!=null)
                        {
//                            System.out.println(chatMain.getMsgList().getMassageList(massageListData.getReceiver_id()).getMassagelist());
//                            System.out.println(chatMain.getMsgList().getMassageList(massageListData.getReceiver_id()).getMassagelist().size());
                            if(chatMain.getMsgList().getMassageList(massageListData.getReceiver_id()).getMassagelist().size()!=0)  chatWithStage.setStage(chatMain.getMsgList().getMassageList(massageListData.getReceiver_id()).getMassagelist());
                        }
                        else {
                            System.out.println("已经有界面了，不管");
                        }
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Friend_List_From_Group))
                {
                    //得到了群聊的好友列表
                    GroupData groupData=(GroupData) massage.getT();
                    System.out.println("设置群聊"+groupData.getGroup_id()+"的好友列表");
                    ChatMain chatMain=Main.AllContronller.getChatMainController();
                    chatMain.AddGroupFriendList(groupData.getGroup_id(),groupData.getGroup_friend_list());

                    Platform.runLater(() -> {
                        GroupStage groupStage=Main.AllContronller.getGroupStage(groupData.getGroup_id());
                        if(groupStage!=null)
                        {
                            groupStage.setAllFriend(groupData.getGroup_friend_list());
                        }
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Chat_Massage_From_Group))
                {
                    //读取到更多的聊天记录
                    MassageListData massageListData=(MassageListData) massage.getT();

                    ChatMain chatMain=Main.AllContronller.getChatMainController();
                    chatMain.getMsgList().addToMap(massageListData.getReceiver_id(),massageListData);

                    System.out.println("正在读取群聊的消息记录");

                    Platform.runLater(() -> {
                        GroupStage groupStage=Main.AllContronller.getGroupStage(massageListData.getReceiver_id());
                        if(groupStage!=null)
                        {
                            groupStage.setMassage(massageListData.getMassagelist());
                        }
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Change_Information_Success))
                {
                    event finalMassage1 = massage;
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.changeMydata((PrivateInformationData) finalMassage1.getT());
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Friend_Information_From_Group))
                {
                    //返回好友的聊天信息了
                    GroupFriendData groupFriendData=(GroupFriendData) massage.getT();
                    GroupStage groupStage=Main.AllContronller.getGroupStage(groupFriendData.getGroup_id());

                    System.out.println("群聊id为"+groupFriendData.getGroup_id());
                    if(groupStage!=null)
                    {
                        groupStage.changeFriendMap(groupFriendData.getId(),groupFriendData);
                    }
                    else
                    {
                        //说明没有这个窗口，需要在chatmian里面去修改
                        System.out.println("控制类为空");
                    }

                }
                else if(massage.getType().equals(MassageType.Return_Delete_Group_Success))
                {
                    //请求解散群聊成功
                    event finalMassage7 = massage;
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("提示");
                        alert.setHeaderText(null);
                        alert.setContentText("您的群聊已经解散，或者你已经被移出群聊!");
                        alert.showAndWait();
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        GroupData groupData=(GroupData) finalMassage7.getT();
                        chatMain.ExitGroup(groupData);
                    });
                }
                else if(massage.getType().equals(MassageType.Delete_Group))
                {
                    //别人解散群聊了
                    event finalMassage7 = massage;
                    Platform.runLater(() -> {
                        GroupData groupData=(GroupData) finalMassage7.getT();
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("成功");
                        alert.setHeaderText(null);
                        alert.setContentText("群聊"+groupData.getGroup_id()+"已经被解散！");
                        alert.showAndWait();
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.ExitGroup(groupData);
                        System.out.println("主界面正在刷新");
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Delete_Group_People_Success))
                {
                    //说明需要删掉群聊的里面的人
                    GroupFriendData groupFriendData=(GroupFriendData)massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.deleteGroupFriend(groupFriendData);
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Invite_Other_To_Group_Success)) {
                    //邀请他人进群成功啦

                    event finalMassage9 = massage;
                    Platform.runLater(() -> {
                        GroupFriendData groupFriendData=(GroupFriendData) finalMassage9.getT();
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("成功");
                        alert.setHeaderText(null);
                        alert.setContentText("邀请成功！");
                        alert.showAndWait();
                        GroupStage groupStage=Main.AllContronller.getGroupStage(groupFriendData.getGroup_id());
                        groupStage.addFriend(groupFriendData);
                    });
                }
                else if(massage.getType().equals(MassageType.Add_Group_People))
                {
                    //需要刷新好友界面
                    GroupFriendData groupFriendData=(GroupFriendData)massage.getT();
                    GroupStage groupStage=Main.AllContronller.getGroupStage(groupFriendData.getGroup_id());
                    if(groupStage!=null)
                    {
                        Platform.runLater(() -> {
                            groupStage.addFriend(groupFriendData);
                        });
                    }
                    else
                    {
                        //如果此时没有打开，也是需要考虑的，因为已经缓存到数组里面，可能就不会刷新
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        ArrayList<PrivateInformationData> privateInformationArrayList=chatMain.getPrivateInformationArry();
                        chatMain.ApendGroupFriendListById(groupFriendData.getGroup_id(),groupFriendData);
                    }
                }
                else if(massage.getType().equals(MassageType.Change_GroupData))
                {
                    //这里需要修改自己的信息和好友列表的信息，分成俩步骤，先该自己的信息
                    System.out.println("接受到了需要修改群聊身份的消息");
                    ChangeGroupFriendListData changedata=(ChangeGroupFriendListData)massage.getT();
                    ChatMain chatMain=Main.AllContronller.getChatMainController();
                    Platform.runLater(() -> {
                        chatMain.changeGroupIdentity(changedata.getGroup_id(),changedata.getIdentity());

                        if(changedata.getArrayList()!=null) chatMain.changeGroupFriendListIdentity(changedata.getArrayList());
                    });
                }
                else if(massage.getType().equals(MassageType.Change_Group_Friend_List))
                {
                    System.out.println("收到了需要更改好友列表的信息");
                    ChangeGroupFriendListData changedata=(ChangeGroupFriendListData)massage.getT();
                    ChatMain chatMain=Main.AllContronller.getChatMainController();
                    Platform.runLater(() -> {
                        if(changedata.getArrayList()!=null)  chatMain.changeGroupFriendListIdentity(changedata.getArrayList());
                    });
                }
                else if(massage.getType().equals(MassageType.Return_Set_Other_Group_Owner_Fail))
                {
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("失败");
                        alert.setHeaderText(null);
                        alert.setContentText("设置其他人为群主失败，请检查网络连接！");
                        alert.showAndWait();
                    });
                }
                else if(massage.getType().equals(MassageType.Add_Common_Sentence_Success))
                {
                    CommonSentenceData commonSentenceData=(CommonSentenceData)massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.addSentence(commonSentenceData);
                    });
                }
                else if(massage.getType().equals(MassageType.Add_Common_Sentence_Fail))
                {
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("失败");
                        alert.setHeaderText(null);
                        alert.setContentText("添加失败，请检查网络连接！");
                        alert.showAndWait();
                    });
                }
                else if(massage.getType().equals(MassageType.Delete_Common_Sentence_Success))
                {
                    CommonSentenceData commonSentenceData=(CommonSentenceData)massage.getT();
                    Platform.runLater(() -> {
                        ChatMain chatMain=Main.AllContronller.getChatMainController();
                        chatMain.deleteSentence(commonSentenceData);
                    });
                }
                else if(massage.getType().equals(MassageType.Delete_Common_Sentence_Fail))
                {
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("失败");
                        alert.setHeaderText(null);
                        alert.setContentText("删除失败！");
                        alert.showAndWait();
                    });
                }
            }

        } catch (IOException | ClassNotFoundException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
